package com.webapp.controller;

import com.webapp.model.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * This doPost section is for login getting the login parameters from the
	 * login.jsp! 
	 */
	@SuppressWarnings("deprecation")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// get the session
		HttpSession session = request.getSession();
		
		/**
		 * Get the user name and parameters
		 */
		String user =  request.getParameter("userNameID");
		String password = request.getParameter("passwordID");
		
		/**
		 * Init a new login model object
		 */
		LoginModel lg = new LoginModel();
		
		/**
		 * test authetication
		 */
		
		String test = lg.checkAuthentication(user, password);
		if(test == "true") {
			User theUser = lg.getUserData(user);
			session.setAttribute("UserObject", theUser);
			//get the request dispatcher
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/homepage.jsp");
						
			//forward to the jsp file to display
			dispatcher.forward(request, response);	
				
		} else if(test == "false") {
			session.setAttribute("UserObject", null);
				
			//redirect
			response.sendRedirect("login.jsp?login=false");
		} else {
			List<String> errorList = new ArrayList();
			errorList.add("Database Connection Error");
			errorList.add("Login Model");
			session.putValue("ErrorObject",errorList);
			response.sendRedirect("error.jsp");
		}
	}
}
